package com.my.study.java.consumer;

import com.my.study.common.constant.TopicConstants;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * @author Carlos
 * @version 1.0
 * @Description 一个分区对应一个消费线程
 * @date 2021/7/25 13:07
 **/
public class PositionConsumer {
    private static final String BROKER_LIST = "47.98.50.37:9092";
    private static final String GROUP_ID = "group.demo";

    private static Properties initConfig() {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        props.put(ConsumerConfig.CLIENT_ID_CONFIG, "consumer.id.demo");

        return props;
    }

    public static void main(String[] args) {
        Properties prop = initConfig();
        int consumerThreadNum = 4;
        for (int i = 0; i < consumerThreadNum; i++) {
            new KafkaConsumerThread(prop, TopicConstants.TOPIC02).start();
        }
    }


    static class KafkaConsumerThread extends Thread {
        private KafkaConsumer<String, String> kafkaConsumer;

        public KafkaConsumerThread(Properties prop, String topic) {
            this.kafkaConsumer = new KafkaConsumer<String, String>(prop);
            this.kafkaConsumer.subscribe(Collections.singletonList(topic));

        }


        @Override
        public void run() {
            try {
                while (true) {
                    // 拉取消息
                    ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100));

                    for (ConsumerRecord<String, String> record : records) {
                        // to deal record
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                kafkaConsumer.close();
            }
        }
    }



}
